import { createRouter, createWebHashHistory } from "vue-router";

const routes = [
  {
    path: "/",
    name: "Home",
    component: () => import("../views/home/Home"),
  },
  {
    path: "/shop/:id",
    name: "Shop",
    component: () => import("../views/shop/Shop"),
  },
  {
    path: "/shop/cartList",
    name: "CartList",
    component: () => import("../views/cartlist/CartList"),
  },
  {
    path: "/orderList",
    name: "OrderList",
    component: () => import("../views/orderList/OrderList"),
  },
  {
    path: "/my",
    name: "My",
    component: () => import("../views/my/My"),
  },
  {
    path: "/orderConfirmation/:id",
    name: "OrderConfirmation",
    component: () => import("../views/orderConfirmation/OrderConfirmation"),
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/login/Login"),
    beforeEnter(to, from, next) {
      const { isLogin } = localStorage;
      isLogin ? next({ name: "Home" }) : next();
    },
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("../views/register/Register"),
    beforeEnter(to, from, next) {
      const { isLogin } = localStorage;
      isLogin ? next({ name: "Home" }) : next();
    },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  const { isLogin } = localStorage;
  !isLogin && to.name !== "Login" && to.name !== "Register"
    ? next({ name: "Login" })
    : next();
});

export default router;
